package com.holic.spring.custom.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.holic.spring.custom.config.GraphQLSource;
import com.holic.spring.custom.holder.DataHolder;
import graphql.ExecutionInput;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.GraphQLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ClassName GraphQLController
 * @Description
 * @Author Neil
 * @Date 2024/11/12 16:25
 * @Version V1.0
 **/
@RestController
@RequestMapping("/graphql")
public class GraphQLController {

    @Autowired
    private GraphQLSource graphQLSource;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public String execute(@RequestBody Map<String, Object> requestBody, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExecutionInput executionInput = ExecutionInput.newExecutionInput()
                .query(requestBody.get("query").toString())
                .variables(requestBody.containsKey("variables") ? (Map<String, Object>) requestBody.get("variables") : null)
                .build();
        GraphQLContext context = executionInput.getGraphQLContext();
        context.put("request", request);
        context.put("response", response);
        ExecutionResult executionResult = graphQLSource.getGraphQL().execute(executionInput);

        return objectMapper.writeValueAsString(executionResult.toSpecification());
    }

}
